package com.example.kai.uno;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ResetPasswords extends AppCompatActivity {
    private MyDBHelper dbHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.resetpasswords);
        Button botton = findViewById(R.id.button5);
        final EditText editText=findViewById(R.id.editText6);
        final EditText editText1=findViewById(R.id.editText7);
        final EditText editText2=findViewById(R.id.editText8);

        botton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editText.length()==0||editText1.length()==0||editText2.length()==0)
                    Toast.makeText(ResetPasswords.this,"用户名或密码为空",Toast.LENGTH_SHORT).show();
                else{
                if (CheckIsDataAlreadyInDBorNot(editText.toString()) == false)
                    Toast.makeText(ResetPasswords.this, "用户名不存在", Toast.LENGTH_SHORT).show();
                else {
                    SQLiteDatabase db = dbHelper.getReadableDatabase();
                    ContentValues values = new ContentValues();
                    values.put("password", editText1.getText().toString());
                    if (editText1.getText().toString().equals(editText2.getText().toString()))
                        db.update("userData", values, "name = ?", new String[]{editText.getText().toString()});
                    else {
                        Toast.makeText(ResetPasswords.this, "两次输入密码不一致", Toast.LENGTH_SHORT).show();
                        editText1.setText(null);
                        editText2.setText(null);
                    }
                }
            }}});

    }
    public boolean CheckIsDataAlreadyInDBorNot(String value){
        SQLiteDatabase db=dbHelper.getWritableDatabase();
        String Query = "Select * from userData where name =?";
        Cursor cursor = db.rawQuery(Query,new String[] { value });
        if (cursor.getCount()>0){
            cursor.close();
            return  true;
        }
        cursor.close();
        return false;
    }
}
